import logging
from flask import Flask, request, jsonify
from paho.mqtt import client as mqtt
# client在可以发布和订阅消息之前必须要先连接到broker代理
# 连接由client发起
# broke地址
broker = "aq.wisdiot.com"
# 端口
port = 1883

# 回调客户机实例
client_id = f'mqtt_down'

server = Flask(__name__)

# log日志
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


# 连接回调函数
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print("Failed to connect, return code %d\n", rc)


#   断开链接回调
def on_disconnect(client, userdata, rc):
    print("Unexpected disconnection rc = " + str(rc))
    pass


def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))


#   订阅回调
def on_subscribe(client, userdata, mid, granted_qos):
    print("On Subscribed: qos = %d" % granted_qos)
    pass


#   取消订阅回调
def on_unsubscribe(client, userdata, mid, granted_qos):
    print("On unSubscribed: qos = %d" % granted_qos)
    pass


#   发布消息回调
def on_publish(client, userdata, mid):
    print("On onPublish: qos = %d" % mid)
    pass


# 发布消息回调
def publish(client,topic,mqtt_content):
    result = client.publish(topic, mqtt_content, qos=0)
    status = result[0]
    if status == 0:
        logging.debug(f"Send to topic `{topic}`")
    else:
        logging.debug(f"Failed to send message to topic {topic}")


# mqtt客户端
def mqtt_client(broker,port,topic,mqtt_content):
    # 初始化客户机
    client = mqtt.Client()
    # 调用连接回调函数
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish
    client.on_disconnect = on_disconnect
    client.on_unsubscribe = on_unsubscribe
    client.on_subscribe = on_subscribe
    # 连接
    client.connect(broker, port)
    # 启用进程保持连接
    client.loop_start()
    # client.username_pw_set(username, password=None)
    # 调用完loop之后再调用publish
    return publish(client,topic,mqtt_content)


